package handler

import (
	"time"

	"github.com/gin-gonic/gin"

	"hrms-api/model"
)

// EmployeeRequest 员工请求结构体
type EmployeeRequest struct {
	UserID       uint      `json:"user_id" binding:"required"`         // 关联用户ID
	Name         string    `json:"name" binding:"required,max=50"`     // 员工姓名，最大长度50
	DepartmentID uint      `json:"department_id" binding:"required"`   // 部门ID
	Position     string    `json:"position" binding:"required,max=50"` // 职位，最大长度50
	Salary       float64   `json:"salary" binding:"required"`          // 基本薪资
	HireDate     time.Time `json:"hire_date"`                          // 入职日期
	Status       *int      `json:"status"`                             // 员工状态(1-在职,0-离职)，可选
}

// ListEmployees 获取员工列表
func ListEmployees(c *gin.Context) {
	var employees []model.Employee
	query := model.DB.Model(&model.Employee{})

	// 支持按部门ID筛选
	if departmentID := c.Query("department_id"); departmentID != "" {
		query = query.Where("department_id = ?", departmentID)
	}

	// 支持按职位筛选
	if position := c.Query("position"); position != "" {
		query = query.Where("position LIKE ?", "%"+position+"%")
	}

	// 支持按状态筛选(1-在职, 0-离职)
	if status := c.Query("status"); status != "" {
		query = query.Where("status = ?", status)
	}

	// 预加载关联数据
	query = query.Preload("User").Preload("Department")

	if err := query.Find(&employees).Error; err != nil {
		InternalServerError(c, "Failed to get employee list")
		return
	}
	Success(c, employees)
}

// CreateEmployee 创建员工记录
func CreateEmployee(c *gin.Context) {
	var req EmployeeRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		BadRequest(c, "Invalid request parameters")
		return
	}

	// 验证用户ID是否存在
	var user model.User
	if err := model.DB.First(&user, req.UserID).Error; err != nil {
		BadRequest(c, "User ID does not exist")
		return
	}

	// 验证部门ID是否存在
	var department model.Department
	if err := model.DB.First(&department, req.DepartmentID).Error; err != nil {
		BadRequest(c, "Department ID does not exist")
		return
	}

	employee := model.Employee{
		UserID:        req.UserID,
		Name:          req.Name,
		DepartmentID:  req.DepartmentID,
		Position:      req.Position,
		BaseSalary:    req.Salary,
		HireDate:      req.HireDate,
		Status:        1,               // 默认在职状态
		OvertimeRate:  1.5,             // 默认加班费率
		DailySalary:   req.Salary / 22, // 默认按22天工作日计算
		InsuranceRate: 0.08,            // 默认社保费率
		FundRate:      0.07,            // 默认公积金费率
		Allowance:     500,             // 默认补贴
	}

	if err := model.DB.Create(&employee).Error; err != nil {
		InternalServerError(c, "Failed to create employee")
		return
	}

	// 按照API文档格式返回响应
	response := gin.H{
		"id":            employee.ID,
		"user_id":       employee.UserID,
		"name":          employee.Name,
		"department_id": employee.DepartmentID,
		"position":      employee.Position,
		"hire_date":     employee.HireDate,
		"created_at":    employee.CreatedAt,
	}

	Success(c, response)
}

// GetEmployee 获取员工详细信息
func GetEmployee(c *gin.Context) {
	id := c.Param("id")
	var employee model.Employee

	// 预加载关联数据
	if err := model.DB.Preload("User").Preload("Department").First(&employee, id).Error; err != nil {
		NotFound(c, "Employee not found")
		return
	}

	// 按照API文档格式返回响应
	response := gin.H{
		"id":      employee.ID,
		"user_id": employee.UserID,
		"name":    employee.Name,
		"department": gin.H{
			"id":   employee.Department.ID,
			"name": employee.Department.Name,
		},
		"position":      employee.Position,
		"base_salary":   employee.BaseSalary,
		"overtime_rate": employee.OvertimeRate,
		"hire_date":     employee.HireDate,
		"user": gin.H{
			"email": employee.User.Email,
			"phone": employee.User.Phone,
		},
		"status":     employee.Status,
		"created_at": employee.CreatedAt,
	}

	Success(c, response)
}

// UpdateEmployee 更新员工信息
func UpdateEmployee(c *gin.Context) {
	id := c.Param("id")

	// 定义更新请求结构体，所有字段都是可选的
	type UpdateEmployeeRequest struct {
		UserID       *uint      `json:"user_id"`
		Name         *string    `json:"name"`
		DepartmentID *uint      `json:"department_id"`
		Position     *string    `json:"position"`
		Salary       *float64   `json:"salary"`
		HireDate     *time.Time `json:"hire_date"`
		Status       *int       `json:"status"`
	}

	var req UpdateEmployeeRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		BadRequest(c, "Invalid request parameters")
		return
	}

	var employee model.Employee
	if err := model.DB.First(&employee, id).Error; err != nil {
		NotFound(c, "Employee not found")
		return
	}

	// 只更新提供的字段
	updates := make(map[string]interface{})

	if req.UserID != nil {
		// 验证用户ID是否存在
		var user model.User
		if err := model.DB.First(&user, *req.UserID).Error; err != nil {
			BadRequest(c, "User ID does not exist")
			return
		}
		updates["user_id"] = *req.UserID
	}

	if req.Name != nil {
		updates["name"] = *req.Name
	}

	if req.DepartmentID != nil {
		// 验证部门ID是否存在
		var department model.Department
		if err := model.DB.First(&department, *req.DepartmentID).Error; err != nil {
			BadRequest(c, "Department ID does not exist")
			return
		}
		updates["department_id"] = *req.DepartmentID
	}

	if req.Position != nil {
		updates["position"] = *req.Position
	}

	if req.Salary != nil {
		updates["base_salary"] = *req.Salary
		// 更新日薪
		updates["daily_salary"] = *req.Salary / 22
	}

	if req.HireDate != nil {
		updates["hire_date"] = *req.HireDate
	}

	if req.Status != nil {
		if *req.Status != 0 && *req.Status != 1 {
			BadRequest(c, "Invalid status value, must be 0 or 1")
			return
		}
		updates["status"] = *req.Status
	}

	// 如果没有要更新的字段
	if len(updates) == 0 {
		BadRequest(c, "No fields to update")
		return
	}

	// 更新员工信息
	if err := model.DB.Model(&employee).Updates(updates).Error; err != nil {
		InternalServerError(c, "Failed to update employee")
		return
	}

	// 重新获取更新后的员工信息
	if err := model.DB.First(&employee, id).Error; err != nil {
		InternalServerError(c, "Failed to retrieve updated employee")
		return
	}

	// 按照API文档格式返回响应
	response := gin.H{
		"id":         employee.ID,
		"position":   employee.Position,
		"salary":     employee.BaseSalary,
		"updated_at": employee.UpdatedAt,
	}

	Success(c, response)
}

// DeleteEmployee 删除员工记录
func DeleteEmployee(c *gin.Context) {
	id := c.Param("id")
	var employee model.Employee
	if err := model.DB.First(&employee, id).Error; err != nil {
		NotFound(c, "Employee not found")
		return
	}

	// 软删除：将状态改为0(离职)而不是真正删除记录
	if err := model.DB.Model(&employee).Update("status", 0).Error; err != nil {
		InternalServerError(c, "Failed to update employee status")
		return
	}

	// 按照API文档格式返回响应
	Success(c, gin.H{
		"code":    200,
		"message": "员工记录删除成功",
	})
}
